package com.michaelbulava.TFS.configuration;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.michaelbulava.TFS.log.FileLogger;
import com.microsoft.tfs.core.TFSConfigurationServer;
import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.util.URIUtils;
import com.microsoft.tfs.util.Check;
import com.microsoft.tfs.util.GUID;
import jetbrains.buildServer.messages.serviceMessages.Message;

import java.net.URI;
import java.text.MessageFormat;
import java.util.Locale;

/**
 * Created by mbulava on 5/6/2015.
 */
public class ProjectPreferences {

    private static final Logger log = FileLogger.getInstance(ProjectPreferences.class);

    private static final String PROJECT_SERVER_URI = "com.michaelbulava.TFS.vcs.projectServerURI";
    private static final String RECONNECT_AT_STARTUP = "com.michaelbulava.TFS.reconnectAtStartUp";
    private static final String PROJECT_IS_OFFLINE = "com.michaelbulava.TFS.projectIsOffline";
    private static final String PROJECT_CHECKED_FOR_TFS = "com.michaelbulava.TFS.projectCheckedForTFS";
    private static final String LAST_SERVER_URI = "com.michaelbulava.TFS.vcs.lastServerURI";
    private static final String LAST_PROJECT_COLLECTION_ID = "com.michaelbulava.TFS.lastProjectCollectionId";
    private static final String LAST_PROJECT_COLLECTION_SEPARATOR = ";";

    private static final String MODULE_IS_OFFLINE_FORMAT = "com.michaelbulava.TFS.moduleOffline_{0}";
    private static final String MODULE_SERVER_URI = "com.michaelbulava.TFS.ModuleURI_{0}";

    private static final String CONNECT_MAPPED_MODULES_AUTOMATICALLY = "com.michaelbulava.TFS.ConnectToModulesAutomatically";
    private static final String ACCEPT_UNTRUSTED_CERTS = "com.michaelbulava.TFS.AcceptUntrustedCertificates";
    private static final String CONNECT_TO_TEAM_EXPLORER_AUTOMATICALLY = "com.michaelbulava.TFS.connectToExplorer";


    private PropertiesComponent prefs;

    public static ProjectPreferences getProjectInstance(Project project){
        return new ProjectPreferences(project);
    }

    private ProjectPreferences(Project project){
        Check.notNull(project, "project");
        this.prefs = PropertiesComponent.getInstance(project);
    }

    private void setBooleanValue(String key, boolean value){
        prefs.setValue(key, Boolean.valueOf(value).toString());
    }



    public void setLastUsedServerURI(URI serverURI){
        Check.notNull(serverURI, "serverURI");
        prefs.setValue(LAST_SERVER_URI, URIUtils.removeTrailingSlash(serverURI).toString());
    }

    public URI getLastUsedServerURI(){
        String uri = prefs.getValue(LAST_SERVER_URI);
        return URIUtils.newURI(uri);
    }

    public void clearLastUsedServerURI(){
        prefs.unsetValue(LAST_SERVER_URI);
    }

    public void clearProjectServerURI(){
        prefs.unsetValue(PROJECT_SERVER_URI);
    }

    public GUID getLastUsedProjectCollection(TFSConfigurationServer configurationServer){
        Check.notNull(configurationServer, "configurationServer");
        if (prefs == null)
            return null;
        return getLastUsedProjectCollection(configurationServer.getBaseURI());
    }

    public GUID getLastUsedProjectCollection(URI configurationServerURI){
        Check.notNull(configurationServerURI, "configurationServerURI");
        if (prefs == null)
            return null;
        String lastCollectionKey = LAST_PROJECT_COLLECTION_ID + LAST_PROJECT_COLLECTION_SEPARATOR +
                configurationServerURI.toString().toLowerCase(Locale.US);
        if (!prefs.isValueSet(lastCollectionKey))
            return null;
        try{
            return new GUID(prefs.getValue(lastCollectionKey));
        } catch(Exception e){
            log.warn("Could not load last project collection preference", e);
        }
        return null;
    }

    public void setLastUsedProjectCollection(TFSTeamProjectCollection connection){
        Check.notNull(connection,"connection");
        if (prefs == null)
            return;
        if (connection.getConfigurationServer() != null){
            setLastUsedProjectCollection(connection.getConfigurationServer().getBaseURI(), connection.getInstanceID());
            setLastUsedServerURI(connection.getConfigurationServer().getBaseURI());
        } else {
            setLastUsedServerURI(connection.getBaseURI());
        }
    }

    public void setLastUsedProjectCollection(URI configurationServerURI, GUID projectCollectionID){
        Check.notNull(configurationServerURI, "configurationServerURI");
        Check.notNull(projectCollectionID, "projectCollectionID");
        if (prefs == null)
            return;
        String lastCollectionKey = LAST_PROJECT_COLLECTION_ID + LAST_PROJECT_COLLECTION_SEPARATOR +
                configurationServerURI.toString().toLowerCase(Locale.US);
        prefs.setValue(lastCollectionKey, projectCollectionID.toString());
    }




    public void setProjectServerURI(URI serverURI){
        Check.notNull(serverURI, "serverURI");
        prefs.setValue(PROJECT_SERVER_URI, URIUtils.removeTrailingSlash(serverURI).toString());
    }

    public URI getProjectServerURI(){
        String uri = prefs.getValue(PROJECT_SERVER_URI);
        return URIUtils.newURI(uri);
    }

    public void setReconnectAtStartup(boolean value){
        setBooleanValue(RECONNECT_AT_STARTUP, value);
    }

    public boolean getReconnectAtStartup(){
        return prefs.getBoolean(RECONNECT_AT_STARTUP, true);
    }

    public void setProjectIsOffline(boolean value){
        setBooleanValue(PROJECT_IS_OFFLINE, value);
    }

    public boolean getProjectIsOffline(){
        return prefs.getBoolean(PROJECT_IS_OFFLINE, false);
    }


    public boolean getModuleIsOffline(Module module){
        return prefs.getBoolean(MessageFormat.format(MODULE_IS_OFFLINE_FORMAT, new Object[] { module.getName()}), false);
    }

    public void setModuleIsOffline(Module module, boolean value){
        setBooleanValue(MessageFormat.format(MODULE_IS_OFFLINE_FORMAT, new Object[] { module.getName() }), value);
    }

    public URI getModuleServerURI(Module module){
        String value = prefs.getValue(MessageFormat.format(MODULE_SERVER_URI, new Object[] { module.getName() }));
        if (value != null)
            return URIUtils.newURI(value);
        return null;
    }

    public void setModuleServerURI(Module module, URI serverURI){
        if (serverURI == null){
            prefs.unsetValue(MessageFormat.format(MODULE_SERVER_URI, new Object[] { module.getName() }));
        } else {
            prefs.setValue(MessageFormat.format(MODULE_SERVER_URI, new Object[] { module.getName() }),
                    URIUtils.removeTrailingSlash(serverURI).toString());
        }
    }


    public boolean getReconnectModules(){
        return prefs.getBoolean(CONNECT_MAPPED_MODULES_AUTOMATICALLY, true);
    }

    public void setReconnectModule(boolean value){
        setBooleanValue(CONNECT_MAPPED_MODULES_AUTOMATICALLY, value);
    }

    public boolean getAcceptUntrustedCerts(){
        return prefs.getBoolean(ACCEPT_UNTRUSTED_CERTS, false);
    }

    public void setAcceptUntrustedCerts(boolean value){
        setBooleanValue(ACCEPT_UNTRUSTED_CERTS, value);
    }

    public boolean getConnectTeamExplorer(){
        return prefs.getBoolean(CONNECT_TO_TEAM_EXPLORER_AUTOMATICALLY, true);
    }

    public void setConnectTeamExplorer(boolean value){
        setBooleanValue(CONNECT_TO_TEAM_EXPLORER_AUTOMATICALLY, value);
    }
}

